import {
  forceSimulation,
  forceManyBody,
  forceCenter,
  forceLink,
  forceCollide,
  forceX,
  forceY
} from "d3-force";
import { select } from "d3-selection";

export default function main({ id, data, width, height, onClick }) {
  const svg = select(id)
    .attr("width", width)
    .attr("height", height);

  const len = data.length;
  let links = [];
  for (let i = 0; i < len - 1; i++) {
    for (let j = 0; j < len - 1; j++) {
      if (i === j) continue;
      links.push({ source: i, target: j });
    }
  }

  forceSimulation(data)
    .velocityDecay(0.2)
    .force("x", forceX().strength(0.002))
    .force("y", forceY().strength(0.002))
    .force(
      "collide",
      forceCollide()
        .radius(function(d) {
          return d.r + 0.5;
        })
        .iterations(2)
    )
    // .force("charge", forceManyBody().strength(-30))
    .force("center", forceCenter(width / 2 - 50, height / 2 - 20))
    // .force("collision", forceCollide(35))
    .force("link", forceLink(links).distance(240))
    .on("tick", ticked);

  function ticked() {
    var col = svg.selectAll("g").data(data);
    const g = col.enter().append("g");

    g.append("foreignObject")
      .attr("width", d => d.width)
      .attr("height", 34)
      .append("xhtml:p")
      .on("click", onClick)
      .attr("class", d => (d.index === 0 ? "name tagActive" : "name"))
      .text(d => d.short);

    col
      .select("foreignObject")
      .attr("x", d => d.x)
      .attr("y", d => d.y);
  }
}
